package com.oig.sys.base.service.impl;

import com.oig.common.constants.CommonEnum;
import com.oig.common.exception.BadRequestException;
import com.oig.sys.base.dao.ITbCurrencyDao;
import com.oig.sys.base.dto.CurrencyDto;
import com.oig.sys.base.entity.TbCurrency;
import com.oig.sys.base.service.ITbCurrencyService;
import com.oig.sys.base.vo.CurrencyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wuxl
 */
@Service
public class TbCurrencyServiceImpl implements ITbCurrencyService {

	private final ITbCurrencyDao tbCurrencyDao;

	@Autowired
	public TbCurrencyServiceImpl( ITbCurrencyDao tbCurrencyDao){
		 this.tbCurrencyDao = tbCurrencyDao;
	}


	@Transactional
	@Override
	public CurrencyVo addTbCurrency(CurrencyDto currencyDto) {
		TbCurrency currency = this.tbCurrencyDao.getByCode(currencyDto.getCode());
		if (currency!=null){
			throw new BadRequestException("编码重复") ;
		}
		currency = new TbCurrency();
		BeanUtils.copyProperties(currencyDto, currency);
		currency.setStatus(CommonEnum.CommonStatusEnum.OK.getCode());
		this.tbCurrencyDao.save(currency);
		CurrencyVo currencyVo = new CurrencyVo();
		BeanUtils.copyProperties(currency,currencyVo);
		return currencyVo;
	}

	@Transactional
	@Override
	public CurrencyVo updateCurrency(CurrencyDto currencyDto) {
		TbCurrency currency = this.tbCurrencyDao.getByCode(currencyDto.getCode());
		currency.setName(currencyDto.getName());
		currency.setEnName(currencyDto.getEnName());
		currency.setSymbol(currencyDto.getSymbol());
		currency.setAmountPrecision(currencyDto.getAmountPrecision());
		currency.setPricePrecision(currencyDto.getPricePrecision());
		this.tbCurrencyDao.save(currency) ;
		CurrencyVo currencyVo = new CurrencyVo();
		BeanUtils.copyProperties(currency,currencyVo);
		return currencyVo;
	}

	@Transactional
	@Override
	public void delCurrency(String code) {
		//this.tbCurrencyDao.deleteByCode(code);
		TbCurrency currency = this.tbCurrencyDao.getByCode(code);
		if (currency!=null){
			this.tbCurrencyDao.delete(currency);//本身是单个的，为了jpa审计能记录
		}
	}

	@Override
	public CurrencyVo getCurrency(String code) {
		TbCurrency currency = this.tbCurrencyDao.getByCode(code);
		if (currency!=null){
			CurrencyVo currencyVo = new CurrencyVo();
			BeanUtils.copyProperties(currency,currencyVo);
			return currencyVo;
		}
		return null;
	}

	@Override
	public List<CurrencyVo> listAll(String status) {
		return this.tbCurrencyDao.findAllForVo(status);
	}
}
